package com.it.cloud.modules.job.utils;

import cn.hutool.core.date.DateUtil;
import com.it.cloud.common.constants.JobConstant;
import com.it.cloud.common.utils.SpringContextUtils;
import com.it.cloud.modules.job.entity.ScheduleJobEntity;
import com.it.cloud.modules.job.entity.ScheduleJobLogEntity;
import com.it.cloud.modules.job.service.IScheduleJobLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
import java.lang.reflect.Method;


/**
 * <p>
 * 定时任务
 * </p>
 *
 * @author 司马缸砸缸了
 * @since 2019-07-25
 */
@Slf4j
public class ScheduleJob extends QuartzJobBean {

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        ScheduleJobEntity scheduleJob = (ScheduleJobEntity) context.getMergedJobDataMap()
                .get(JobConstant.JOB_PARAM_KEY);

        //获取spring beanScheduleJobLogServiceImpl
        IScheduleJobLogService scheduleJobLogService = (IScheduleJobLogService) SpringContextUtils.getBean("scheduleJobLogServiceImpl");

        //数据库保存执行记录
        ScheduleJobLogEntity jobLog = new ScheduleJobLogEntity();
        jobLog.setJobId(scheduleJob.getId());
        jobLog.setBeanName(scheduleJob.getBeanName());
        jobLog.setParams(scheduleJob.getParams());
        jobLog.setCreateTime(DateUtil.date().toTimestamp());

        //任务开始时间
        long startTime = System.currentTimeMillis();

        try {
            //执行任务
            log.debug("任务准备执行，任务ID：" + scheduleJob.getId());

            Object target = SpringContextUtils.getBean(scheduleJob.getBeanName());
            Method method = target.getClass().getDeclaredMethod("run", String.class);
            method.invoke(target, scheduleJob.getParams());

            //任务执行总时长
            long times = System.currentTimeMillis() - startTime;
            jobLog.setTimes((int) times);
            //任务状态  0：成功  1：失败
            jobLog.setStatus(0);

            log.debug("任务执行完毕，任务ID：" + scheduleJob.getId() + "  总共耗时：" + times + "毫秒");
        } catch (Exception e) {
            log.error("任务执行失败，任务ID：" + scheduleJob.getId(), e);

            //任务执行总时长
            long times = System.currentTimeMillis() - startTime;
            jobLog.setTimes((int) times);

            //任务状态  0：成功  1：失败
            jobLog.setStatus(1);
            jobLog.setError(StringUtils.substring(e.toString(), 0, 2000));
        } finally {
            scheduleJobLogService.save(jobLog);
        }
    }
}
